package com.example.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.common.util.core.resultbody.AjaxResult;
import com.example.common.util.enums.BusinessEnum;
import com.example.service.util.utils.JwtUtils;
import com.example.common.util.utils.StringUtils;
import com.example.service.util.constants.GatewayConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @Author juzipi
 * @Date 2021/7/19 8:24
 * @Info
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();

        if (antPathMatcher.match(GatewayConstants.PATH_INNER_MATCH,path)){
            log.error(BusinessEnum.UN_AUTHORITY.getInfo());
            return errorResponse(response,BusinessEnum.UN_AUTHORITY);
        }

        if (antPathMatcher.match(GatewayConstants.PATH_AUTH_MATCH,path)){
            if (StringUtils.isNull(this.getUserId(request))){
                log.error(BusinessEnum.NOT_LOGIN.getInfo());
                return errorResponse(response,BusinessEnum.NOT_LOGIN);
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }


    /**
     * 接口鉴权返回失败数据
     * @param response
     * @param businessEnum
     * @return
     */
    private Mono<Void> errorResponse(ServerHttpResponse response, BusinessEnum businessEnum) {
        AjaxResult error = AjaxResult.error(Integer.parseInt(businessEnum.getCode()), businessEnum.getInfo());
        byte[] bits = JSONObject.toJSONString(error).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }


    /**
     * 根据token获取用户id
     * @param request
     * @return
     */
    private Long getUserId(ServerHttpRequest request){
        String token = request.getHeaders().getFirst(GatewayConstants.TOKEN);
        if (StringUtils.isNotEmpty(token)){
            return JwtUtils.getUserId(token);
        }
        return null;
    }

}
